package com.kzd.btgame.utils;

import android.content.Context;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class ApkFile {

    /**
     *
     * @param file
     *            需要写入数据的apk文件
     * @param comment
     *            需要写入的数据
     */
    public static void writeApk(File file, String comment) {
        ZipFile zipFile = null;
        ByteArrayOutputStream outputStream = null;
        RandomAccessFile accessFile = null;
        try {
            zipFile = new ZipFile(file);
//            String zipComment = zipFile.getComment();
//            // 判断comment区域是否已经有数据了
//            if (zipComment != null)
//                return;
            byte[] byteComment = comment.getBytes();
            outputStream = new ByteArrayOutputStream();
            // 将数据写入输出流
            outputStream.write(byteComment);
            // 紧接着写入数据大小
            outputStream.write(short2Stream((short) byteComment.length));

            byte[] data = outputStream.toByteArray();
            accessFile = new RandomAccessFile(file, "rw");
            // 跳到comment区域
            accessFile.seek(file.length() - 2);
            // 先写入数据大小
            accessFile.write(short2Stream((short) data.length));
            // 写入数据
            accessFile.write(data);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (zipFile != null)
                    zipFile.close();
                if (outputStream != null)
                    outputStream.close();
                if (accessFile != null)
                    accessFile.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * short转换成字节数组
     *
     * @param data
     * @return
     */
    private static byte[] short2Stream(short data) {
        ByteBuffer buffer = ByteBuffer.allocate(2);
        buffer.order(ByteOrder.LITTLE_ENDIAN);
        buffer.putShort(data);
        buffer.flip();
        return buffer.array();
    }


    /**
     * 读取comment区域数据
     *
     * @param
     * @return
     */
    public static String readApk(Context context) {
        // 获取文件路径
        File file = new File(context.getPackageCodePath());
        byte[] bytes = null;
        RandomAccessFile accessFile = null;
        try {
            accessFile = new RandomAccessFile(file, "r");
            long index = accessFile.length();

            bytes = new byte[2];
            // 获取comment文件的位置
            index = index - bytes.length;
            accessFile.seek(index);
            // 获取comment中写入数据的大小byte类型
            accessFile.readFully(bytes);
            // 将byte转换成大小
            int contentLength = stream2Short(bytes, 0);
            // 创建byte[]数据大小来存储写入的数据
            bytes = new byte[contentLength];
            index = index - bytes.length;
            accessFile.seek(index);
            // 读取数据
            accessFile.readFully(bytes);
            return new String(bytes, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (accessFile != null) {
                try {
                    accessFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 字节数组转换成short
     *
     * @param stream
     * @param offset
     * @return
     */
    private static short stream2Short(byte[] stream, int offset) {
        ByteBuffer buffer = ByteBuffer.allocate(2);
        buffer.order(ByteOrder.LITTLE_ENDIAN);
        buffer.put(stream[offset]);
        buffer.put(stream[offset + 1]);
        return buffer.getShort(0);
    }

    /**
     * 获取META-INFO下的渠道
     *
     * @param context 上下文
     * @return channel
     */
    public static String readMETAINFO(Context context,String flag) {
        if (context == null) {
            return null;
        }
        StringBuilder channelMsg = new StringBuilder();
        ZipFile zipFile = null;
        try {
            zipFile = new ZipFile(context.getApplicationInfo().sourceDir);
            Enumeration<?> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = ((ZipEntry) entries.nextElement());
                String entryName = entry.getName();
                if (entryName.startsWith(flag)) {
                    long size = entry.getSize();
                    if (size <= 0) {
                        return null;
                    }
                    BufferedReader br = new BufferedReader(new InputStreamReader(zipFile.getInputStream(entry)));
                    String line;
                    while ((line = br.readLine()) != null) {
                        channelMsg.append(line);
                    }
                    br.close();
                    if (channelMsg.length() <= 0) {
                        return null;
                    }
                    return channelMsg.toString();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (zipFile != null) {
                try {
                    zipFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }

}
